const { article: ArticleModel, tag: TagModel } = require("../models")

module.exports = {
    async create(ctx) {
        // 新建文章
        const { title, content, tags } = ctx.request.body
        const tagList = tags.map(t => ({ name: t }))
        const data = await ArticleModel.create({ title, content, tags: tagList }, { include: [TagModel] })
        ctx.body = { code: 200, message: "成功创建文章", data }
    },

    async getArticleList(ctx) {
        // 文章列表
        const { page = 1, pageSize = 10 } = ctx.request.body
        const offset = (page - 1) * pageSize
        const data = await ArticleModel.findAll({
            attributes: ["id", "content", "title"],
            include: [{ model: TagModel, attributes: ["name"] }],
            offset,
            limit: pageSize
        })

        const total = await ArticleModel.count()
        ctx.body = { success: true, data: { list: data, total } }
    }
}
